// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }); // 使用当前云环境

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); 
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0'); 
  const minutes = date.getMinutes().toString().padStart(2, '0'); 
  return `${year}.${month}.${day} ${hours}:${minutes}`;
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  const db = cloud.database();
  const { avatarUrl, nickname } = event;
  const currentDate = new Date();
  const formattedDate = formatDate(currentDate);

  try {
    // 向数据库添加 openid，并获取响应
    const res = await db.collection('answer_record').add({
      data: {
        openid: openid,
        createdAt: formattedDate, // 可选：记录创建时间
        avatarUrl: avatarUrl,
        nickname: nickname,
      }
    });

    // 返回新插入记录的 _id
    return {
      event,
      openid: wxContext.OPENID,
      appid: wxContext.APPID,
      unionid: wxContext.UNIONID,
      _id: res._id, // 添加这一行以返回新记录的 _id
      message: 'openid 已成功添加到数据库'
    };
  } catch (e) {
    console.error(e);
    return {
      message: '添加 openid 失败',
      error: e
    };
  }
}
